/*
 * @Author: fhw
 * @Date: 2022-04-21 22:43:47
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-02-07 10:57:04
 * @Description: 基础数据仓库
 */
import { Action, getModule, Module, Mutation, VuexModule } from 'vuex-module-decorators'
import store from '@/store'
import {
	ChatRecord,
	ChatUnreadMessage,
	ChatUserGroup,
	ContactsFriends,
	Friends,
	HistorySession,
	User,
} from '@/interface'
import { isTrue } from '@/utils/tools'
import { clone, equals, isEmpty } from 'ramda'
import * as IndexedDB from '@/indexedDB'
export interface Contacts extends ContactsFriends, ChatUserGroup {}
export interface BasicDataState {
	chatUnreadMessage: { [key: number | string]: ChatUnreadMessage }
}
export interface Options {
	value: string | number
	label: string
	type?: number
	title?: string
	[index: string]: any
	children?: Array<this>
	isLeaf?: boolean
	loading?: boolean
}
export interface FriendsVerifyList extends Friends {
	spinning: boolean
}
@Module({ namespaced: true, store, name: 'basicData', dynamic: true })
export class BasicData extends VuexModule implements BasicDataState {
	public chatUnreadMessage: { [key: string | number]: ChatUnreadMessage } = {} //聊天未读消息
	public friendsMessage: { [key: string | number]: number } = {} //聊天未读消息
	public friendsVerifyList: FriendsVerifyList[] = []
	public contacts: Contacts[] = []
	public historySession: HistorySession[] = []
	public userInfo: User = {}
	public friendsRemarksMap: Map<string, string> = new Map()
	/**
	 * 未读好友消息记录总数
	 */
	public unreadFriendsTotalCount = 0
	// 未读消息
	@Mutation
	public async SET_CHATRECORD(data: { [key: number]: ChatUnreadMessage }) {
		this.chatUnreadMessage = data
	}
	// 未读好友消息记录
	@Mutation
	public async SET_FRIENDS(data: { [key: number]: number }) {
		if (!isTrue(data)) {
			this.friendsMessage = data
			return
		}
		for (const key in data) {
			this.friendsMessage[key] = data[key]
		}
	}
	// 未读好友消息记录总数
	@Mutation
	public async SET_UNREADFRIENDSTOTALCOUNT(data: { [key: number]: number }) {
		let count = 0
		const unreadFriends = Object.assign(this.friendsMessage, data)
		for (const key in unreadFriends) {
			count += unreadFriends[key] ?? 0
		}
		this.unreadFriendsTotalCount = count
	}
	//好友验证记录
	@Action
	public async getFriendsVerifyList() {
		const userId = localStorage.getItem('userId') as string
		const { success, data } = await API.blog.chatUserFriends.getUserFriendsList.request({
			userId,
			del: 1,
		})
		if (success && data) {
			this.SET_FRIENDSVERIFYLIST(data)
		}
	}

	// 好友验证记录
	@Mutation
	public async SET_FRIENDSVERIFYLIST(data: FriendsVerifyList[]) {
		this.friendsVerifyList = clone(data).map((item) => {
			return {
				...item,
				spinning: false,
			}
		})
	}
	//获取用户列表
	@Action
	public async getContacts() {
		const userId = localStorage.getItem('userId') as string
		const { success, data } = await API.blog.chatUser.getContacts.request(userId as string)
		if (success && data) {
			this.SET_CONTACTS(data.friend.concat(data.chatUserGroup))
		}
	}

	// 获取用户列表
	@Mutation
	public async SET_CONTACTS(data: Contacts[]) {
		this.contacts = clone(data)
		const tableList = data.map((item) => {
			return {
				// 表名
				tableName: `user-chat-record-${item.friendsId ?? item.groupChat.group_id}`,
				// 主键
				keyPath: 'id',
				autoIncrement: true,
			}
		})
		if (!isEmpty(tableList)) {
			IndexedDB.init('chat', tableList)
		}
	}
	// 获取历史会话
	@Action
	public async getHistorySession() {
		const userId = localStorage.getItem('userId') as string
		const { data, success } = await API.blog.historySession.getHistorySession.request({ userId })
		if (success) {
			this.SET_HISTORYSESSION(data)
		}
	}
	@Mutation
	public async SET_HISTORYSESSION(data: HistorySession[]) {
		this.historySession = clone(data)
		data.forEach((item) => {
			BasicDataModule.friendsRemarksMap?.set(
				item.historicalUserSessionsId as string,
				item.chatUserFriend?.remarks as string
			)
		})
	}
	// 获取用户详情
	@Action
	public async getUserInfo() {
		const userId = localStorage.getItem('userId') as string
		if (!isTrue(userId)) return
		const { success, data } = await API.blog.chatUser.getUserInfo.request({ id: userId })
		if (success) {
			this.SET_USERINFO(data)
		}
	}
	@Mutation
	public async SET_USERINFO(data: User) {
		this.userInfo = clone(data)
		BasicDataModule.getContacts()
	}
	// 更新联系人最新消息
	@Mutation
	public async updateLatestNews(chatRecord: ChatRecord) {
		BasicDataModule.historySession.forEach((item) => {
			if (equals(item.historicalUserSessionsId, chatRecord.to_userId || chatRecord.group_id)) {
				item.latestNews = clone(chatRecord)
			}
		})
	}
	@Mutation
	public async logout() {
		this.chatUnreadMessage = {}
		this.friendsMessage = {}
		this.userInfo = {}
		this.historySession = []
		this.friendsVerifyList = []
		this.contacts = []
		this.unreadFriendsTotalCount = 0
		this.friendsRemarksMap = new Map()
	}
}

export const BasicDataModule = getModule(BasicData)
